
/**************************************************excel插件开始********************************************************/
const ExcelApp ={
    //只导出第1页，不翻页的
    
    exportExcelByApi : function (url,  excelTitleJson, excelName, data, settings) {
        layer.load(0, Object.assign(CONF_LAYER_LOAD, {time:5000}));
        
        if(!settings){
            settings = {
                //页数
                pageNo : 1,
                //拿到的数据json进行封装到arr数组中
                arr : []
            }
        }
        data["pageNo"] = settings.pageNo;
        data["pageSize"] = 10000  //重新设置每页加载数量
        $.getJSON(url, data, function(res){
            //如果有数据
            if(res.data.length > 0){
                //遍历塞入数据
                for(let i = 0;i<res.data.length;i++){
                    settings.arr.push(res.data[i]);
                }
    
                //table.exportFile([],settings.arr , 'xls'); //默认导出 csv，也可以为：xls
                layer.closeAll()
                console.log("导出excel！！！！！！！！！！！！！！！！！！")
                $(".excel-table").table2excel({
                    //exclude: ".noExl",
                    filename: excelName + new Date().toISOString().replace(/[\-\:\.]/g, ""),
                    fileext: ".xls",
                    sheetName: "sheet",
                    excludeFirst:true,
                    excudeLast:true,
                    dataList:settings.arr,
                    dataTitle:excelTitleJson
                });
            }else{
                layer.closeAll()
                layer.msg("当前条件没有数据",{time:1000});
            }
        });
    },
    
    //导出excel时候，把页面的数据分装到一个json数组中，然后使用layui的导出方法导出数据
    exportExcelByPageApi : function (url,  excelTitleJson, excelName, data, settings) {
        layer.load(0, Object.assign(CONF_LAYER_LOAD, {time:5000}));
        if(typeof(data) == "undefined" || data == null){
            console.log("查询条件为空");
            data = JSON.parse("{}");
        }
        
        if(!settings){
            settings = {
                //页数
                pageNo : 1,
                //拿到的数据json进行封装到arr数组中
                arr : []
            }
        }
        data["pageNo"] = settings.pageNo;
        data["pageSize"] = 10000  //重新设置每页加载数量
        $.getJSON(url, data, function(json){
            if(json.data.length <= 0){
                //没有查到数据,不导出
                if(settings.arr.length > 0){
                    //table.exportFile([],settings.arr , 'xls'); //默认导出 csv，也可以为：xls
                    layer.closeAll()
                    console.log("导出excel！！！！！！！！！！！！！！！！！！")
                    $(".layui-table-box").table2excel({
                        //exclude: ".noExl",
                        filename: excelName + new Date().toISOString().replace(/[\-\:\.]/g, ""),
                        fileext: ".xls",
                        sheetName: "sheet",
                        excludeFirst:true,
                        excudeLast:true,
                        dataList:settings.arr,
                        dataTitle:excelTitleJson
                    });
                    
                    //导出后这个页数,初始化
                    settings.pageNo = 1;
                }else{
                    layer.closeAll()
                    layer.msg("当前条件没有数据",{time:1000});
                }
            }else{
                for(var i = 0;i<json.data.length;i++){
                    json.data[i].cardNumber = '卡号：'+json.data[i].cardNumber;
                    // console.log("往arr里面推入：",json.data[i])
                    settings.arr.push(json.data[i]);
                }
                settings.pageNo++;
                data["pageNo"] = settings.pageNo;
                
                //有数据,就再次执行拿数据，回调
                ExcelApp.exportExcel(url, excelTitleJson, excelName, data, settings);
            }
        });
    }
}
    //excel初始化插件应用
;(function ( $, window, document, undefined ) {
    let pluginName = "table2excel",
        defaults = {
            filename: "table2excel",//导出excel的名字
            fileext: ".xls",//导出excel的格式
            sheetName:"sheet",//sheet的名字
            // excludeFirst:false,//是否去除第一列，默认去不掉
            //excudeLast:false,//最后一列是否除去
            dataList:[],//数据，json数组 必填
            dataTitle:{}//表格的头 必填
        };

    // The actual plugin constructor
    function Plugin ( element, options ) {
        this.element = element;
        //extend把后俩个合并到第一个中
        this.settings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {
            let e = this;

            let utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
            e.template = {
                head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
                sheet: {
                    head: "<x:ExcelWorksheet><x:Name>",
                    tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
                },
                mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
                table: {
                    head: "<table>",
                    tail: "</table>"
                },
                foot: "</body></html>"
            };
            e.tableRows = [];
            if(e.settings.dataTitle.length < 0 || e.settings.dataTitle == ""){
                console.log("不可以没有title");
                return false;
            }
            var tempRowsTitle = "";
            //标题行
            tempRowsTitle += "<tr>";
            for(var key in e.settings.dataTitle){
                tempRowsTitle += "<td>" + e.settings.dataTitle[key] + "</td>";
            }
            tempRowsTitle += "</tr>";
            e.tableRows.push(tempRowsTitle);

            //循环数据行
            var listNum = e.settings.dataList.length;
            var list = e.settings.dataList;
            for(var i=0; i < Number(listNum); i++ ){
                var tempRows = "";
                tempRows += "<tr>";
                for(var key in e.settings.dataTitle){
                    tempRows += "<td>" + (typeof(list[i][key]) == "undefined" ? "--" : list[i][key] == null ? "--" : list[i][key]) + "</td>";
                }
                tempRows += "</tr>";
                //每行都添加到里边
                e.tableRows.push(tempRows);
            }

            e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
        },

        tableToExcel: function (table, name, sheetName) {
            var e = this, fullTemplate="", i, link, a;
            e.format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                });
            };
            sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;
            e.ctx = {
                // worksheet: name || "Worksheet",//这个字段无用
                table: table,
                sheetName: sheetName
            };
            fullTemplate= e.template.head;

            fullTemplate += e.template.sheet.head + "hellow world" + e.template.sheet.tail;
            /*if ( $.isArray(table) ) {
                console.log("组装 sheet表")
                for (i in table) {
                    //fullTemplate += e.template.sheet.head + "{" + e.ctx.worksheet + i + "}" + e.template.sheet.tail;
                    fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
                }
            }*/
            fullTemplate += e.template.mid;
            if ( $.isArray(table) ) {
                console.log("组装excel行数据")
                for (i in table) {
                    fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
                }
            }
            fullTemplate += e.template.foot;
            for (i in table) {
                e.ctx["table" + i] = table[i];
            }
            delete e.ctx.table;
            var isIE = /*@cc_on!@*/false || !!document.documentMode; // this works with IE10 and IE11 both :)
            //if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // this works ONLY with IE 11!!!
            if (isIE) {
                if (typeof Blob !== "undefined") {
                    //use blobs if we can
                    fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE
                    fullTemplate = [fullTemplate];
                    //convert to array
                    var blob1 = new Blob(fullTemplate, { type: "text/html" });
                    window.navigator.msSaveBlob(blob1, getFileName(e.settings) );
                } else {
                    //otherwise use the iframe and save
                    //requires a blank iframe on page called txtArea1
                    txtArea1.document.open("text/html", "replace");
                    txtArea1.document.write(e.format(fullTemplate, e.ctx));
                    txtArea1.document.close();
                    txtArea1.focus();
                    sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) );
                }

            } else {
                var blob = new Blob([e.format(fullTemplate, e.ctx)], {type: "application/vnd.ms-excel"});
                window.URL = window.URL || window.webkitURL;
                link = window.URL.createObjectURL(blob);
                a = document.createElement("a");
                a.download = getFileName(e.settings);
                a.href = link;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
            return true;
        }
    };

    function getFileName(settings) {
        let fullExcelName =   settings.filename ? settings.filename : "table2excel" ;
        return fullExcelName+settings.fileext
    }


    $.fn[ pluginName ] = function ( options ) {
        let e = this;
        e.each(function() {
            //console.log(options)
            if ( !$.data( e, "plugin_" + pluginName ) ) {
                $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
            }
        });

        // chain jQuery functions
        return e;
    };

})( jQuery, window, document );
/**************************************************excel插件结束********************************************************/

